import { Text } from '@tarojs/components';
import Taro from '@tarojs/taro';
import { CSSProperties, useMemo, memo } from 'react';
import { font } from '@/utils/font';
import iconData from './iconfont.json';
import './index.scss';

export const iconNames = iconData.glyphs.map(v => v.name);

export interface IconProps {
  /** 字体名称 */
  fontName?: string;
  /** 图标名称 */
  name?: string;
  /**
   * 图标颜色
   */
  color?: string;
  /**
   * 图标尺寸
   */
  size?: number;
  /**
   * class
   */
  className?: string;
  /**
   * 样式
   */
  style?: CSSProperties;
  /**
   * 点击事件
   * @returns
   */
  onClick?: (e) => void;
}

// font.load('MyIcon', 'http:w.ttf')
if (process.env.TARO_ENV !== 'weapp') {
  font.load('MyIcon', require('./iconfont.ttf')); // 本地icon
}

const Icon = memo(({ fontName = 'MyIcon', name, color, size, style, className, ...props }: IconProps) => {
  const _style = useMemo(() => {
    const sty = { ...style };
    if (color) {
      sty.color = color;
    }
    if (size) {
      sty.fontSize = Taro.pxTransform(size);
    }
    return sty;
  }, [color, size, style]);

  const item = iconData.glyphs.find(v => v.name === name);
  if (!item) {
    console.log(`iconfont${name}图标不存在`);
    return null;
  }

  const status = font.useFont(fontName);
  if (!status) {
    return null;
  }

  return (
    <Text className={`${fontName} ${className || ''}`} style={_style} {...props}>
      {String.fromCharCode(item.unicode_decimal)}
    </Text>
  );
});
export default Icon;
